package cn.gailvlun.gll.presentation.main

import android.arch.lifecycle.ViewModel
import android.os.Build
import android.support.annotation.NonNull
import cn.gailvlun.gll.BuildConfig
import cn.gailvlun.gll.Constants
import cn.gailvlun.gll.bean.PlaceHolder
import cn.gailvlun.gll.chatlib.bean.SystemNotification
import cn.gailvlun.gll.chatlib.db.ChatDB2
import cn.gailvlun.gll.chatlib.message.Message
import cn.gailvlun.gll.net.HttpMethods
import cn.gailvlun.gll.net.HttpSubscriber
import cn.gailvlun.gll.net.base.UploadInfoReq
import cn.gailvlun.gll.net.base.friend.FriendNotification
import cn.gailvlun.gll.util.DeviceUtil
import cn.gailvlun.gll.util.LogUtil
import cn.gailvlun.gll.util.RxUtil
import io.reactivex.Flowable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.rxkotlin.Flowables
import io.realm.Realm
import io.realm.RealmResults
import java.util.concurrent.TimeUnit


class MainViewModel: ViewModel {

    var realm: Realm?

    private val systemNotiUnreadResults: RealmResults<SystemNotification>
    private val friendNotiUnreadResults: RealmResults<FriendNotification>
    private val messageUnreadResults: RealmResults<Message>

    val countFlowable: Flowable<Int>

    constructor() : super() {
        this.realm = Realm.getInstance(ChatDB2.getConfiguration())

        systemNotiUnreadResults = realm!!.where(SystemNotification::class.java)


                .equalTo("unread", true)
                .findAllAsync()

        friendNotiUnreadResults = realm!!.where(FriendNotification::class.java)
                .equalTo("status", 0 as Int)
                .findAllAsync()

        messageUnreadResults = realm!!.where(Message::class.java)
                .equalTo("unread", true)
                .findAllAsync()

        countFlowable = Flowables.combineLatest(systemNotiUnreadResults.asFlowable().filter {it.isLoaded},
                friendNotiUnreadResults.asFlowable().filter {it.isLoaded},
                messageUnreadResults.asFlowable().filter {it.isLoaded})
                .map { it.first.count() + it.second.count() + it.third.count() }
                .sample(1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
    }

    fun uploadDeviceInfo(@NonNull registrationId: String) {
        val uploadInfoReq = UploadInfoReq()
        uploadInfoReq.registration_id = registrationId
        uploadInfoReq.device_brand = Build.BRAND
        uploadInfoReq.device_type = Build.MODEL
        uploadInfoReq.device_id = DeviceUtil.getLocaldeviceId()
        uploadInfoReq.version = BuildConfig.VERSION_NAME
        HttpMethods.getBaseService().uploadDeviceInfo(uploadInfoReq)
                .compose(RxUtil.applyScheduler())
                .subscribe(object : HttpSubscriber<PlaceHolder>() {
                    override fun onSuccess(response: PlaceHolder) {

                    }

                    override fun onFailure(errMsg: String, response: PlaceHolder?, code: Int) {

                    }
                })
    }

    private var lastClick: Long = 0

    fun onBackPressed(): Boolean {
        var canExit = false
        val now = System.currentTimeMillis()
        if (now - lastClick < 1000 * Constants.doubleClickDuration) {
            canExit = true
        }
        lastClick = now
        return canExit
    }

    fun closeRealm() {
        realm?.close()
        realm = null
    }

    override fun onCleared() {
        LogUtil.d("mainViewModel $this onCleared")
        super.onCleared()
    }
}